package com.zhz.mall.common.constraints;

import com.google.common.collect.Sets;
import com.zhz.mall.common.annotation.ValueContains;
import com.zhz.mall.common.util.enums.EnumValueResolver;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Set;

public class ValueContainsValidator implements ConstraintValidator<ValueContains, Object> {
    private Set<Object> scope;

    @Override
    public void initialize(ValueContains constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        Class<? extends EnumValueResolver<?, ?>> enums = constraintAnnotation.scopeEnum();
        EnumValueResolver<?, ?>[] enumConstants = enums.getEnumConstants();
        boolean fromValue = constraintAnnotation.isFromValue();
        scope = Sets.newHashSet();
        scope.add(Arrays.stream(enumConstants).map(temp -> {
            if (fromValue) {
                return temp.getValue();
            }
            return temp.getDesc();
        }));
    }

    @Override
    public boolean isValid(Object t, ConstraintValidatorContext constraintValidatorContext) {
        return scope.contains(t);
    }
}
